package com.sencorsta.ids.core.application.zone;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import com.sencorsta.ids.core.configure.SysConfig;
import com.sencorsta.ids.core.tcp.opensocket.OpenMessage;
import com.sencorsta.ids.core.tcp.socket.protocol.RpcMessage;

@SuppressWarnings("unchecked")
public class NodeService {

	private static final int ZONE_MAX_COUTN = SysConfig.getInstance().getInt("zone.maxcount", 1000);


	public static final Map<Integer, Zone> Zones = new ConcurrentHashMap<>();

	public static <T extends Zone> T enter(ZoneUser zoneUser) {
		for (Zone zone : Zones.values()) {
			if (zone.getZoneUsersCount() < ZONE_MAX_COUTN) {
				zone.enter(zoneUser);
				return (T) zone;
			}
		}
		return null;
	}

	public static <T extends Zone> T leave(ZoneUser zoneUser) {
		if (zoneUser == null) {
			return null;
		}
		Zone zone = zoneUser.zone;
		if (zone != null) {
			zone.leave(zoneUser);
		}
		return (T) zone;
	}

	public static void newZone(Zone zone) {
		if (zone != null) {
			Zones.put(zone.getId(), zone);
		}
	}

	public static void delZone(Zone zone) {
		if (zone != null) {
			Zones.remove(zone.getId());
		}
	}

	/**
	 * 给所有进入房间的玩家广播
	 */
	public static void broadcast(RpcMessage msg,String type) {
		for (Zone zone : Zones.values()) {
			zone.broadcast(msg,type);
		}
	}

	public static <T extends Zone> T getZone(int key) {
		return (T) Zones.get(key);
	}

}
